# -*- coding: utf-8 -*-

import hashlib
import random

import pymysql

import myconf


# 验证码生成\检测

class Id_code(object):
    def __init__(self):
        y = 'abcdefghjkmnpqrstuvwxy' + 'abcdefghjkmnpqrstuvwxy'.upper()
        m = [str(random.randint(0, 9)), random.choice(y), random.choice(y), random.choice(y), random.choice(y), random.choice(y), str(random.randint(0, 9))]
        w = ''
        for i in range(0, 5):
            n = random.choice(m)
            w += n
        self.x = w


# 功能是否开启检测
def check_on(func):
    x = func.__name__
    Tag = myconf.config[x]

    def inner(*args, **kwargs):
        if Tag == False:
            return '功能未开启！！！请联系管理员'
        else:
            res = func(*args, **kwargs)
            return res

    return inner


class Backstage:
    @check_on
    def register(self, usr, passwd, q):
        if len(usr) == 0 or len(passwd) == 0 or len(q) == 0:
            return '信息不能为空！！！！'
        try:
            conn = pymysql.connect(user='root', password=myconf.config['DB_PASSWORD'], host=myconf.config['IP'],
                                   database='web', port=myconf.config['DB_PORT'])
            c = conn.cursor()
        except:
            return '配置文件填写错误，请修改正确后，重新运行run.sh安装本应用'

        # 检查账号是否存在！
        usr = usr + '@game.sohu.com'
        sql_usr = '''SELECT name
        from  account 
        where
        name = %s;'''
        try:
            z = c.execute(sql_usr,usr)
            if z != 0:
                c.close()
                conn.close()
                return '账号已经存在！！！！'
        except Exception as e:
            c.close()
            conn.close()
            return e

        # 注册功能！
        pw = hashlib.md5(passwd.encode('utf-8')).hexdigest()
        if len(q) < 8:
            c.close()
            conn.close()
            return '注册失败，你输入的超级密码，必须大于等于8位数！！'
        else:
            question = hashlib.md5(q.encode('utf-8')).hexdigest()
            emial = "1234@qq.com"
            try:
                sql_create = '''
                insert into account(name,password,question,email
                )
                VALUES (%s,%s,%s,%s)
                '''
                c.execute(sql_create,(usr, pw, question, emial))
                conn.commit()
                c.close()
                conn.close()
                data = '注册成功！！！您的账号：%s' % usr + '\n' + '您的密码：%s' % passwd + '\n' + '您的超级密码：%s' % q
                return data
            except Exception as e:
                conn.rollback()
                c.close()
                conn.close()
                return e

    @check_on
    def modify_passwd(self, usr, question_demo, new_passwd):
        if len(usr) == 0 or len(question_demo) == 0 or len(new_passwd) == 0:
            return '输入的信息不能为空！！！'
        try:
            conn = pymysql.connect(user='root', password=myconf.config['DB_PASSWORD'], host=myconf.config['IP'],
                                   database='web', port=myconf.config['DB_PORT'])
            c = conn.cursor()
        except:
            return '配置文件的数据库信息填写错误！！请检查您的数据库IP、密码和端口是否填写正确，然后重新执行run.sh脚本！！'

        # 检察账号是否存在
        usr = usr + '@game.sohu.com'
        question = hashlib.md5(question_demo.encode('utf-8')).hexdigest()
        sql_usr = '''SELECT name,question
        from  account 
        where
        name=%s and question=%s;'''
        try:
            z = c.execute(sql_usr,(usr, question))
            if z == 0:
                c.close()
                conn.close()
                return '账号不存在或输入的超级密码错误，请确认你你输入的是正确的信息！！！'
        except Exception as e:
            c.close()
            conn.close()
            return e

        # 修改密码
        md5_passwd = hashlib.md5(new_passwd.encode('utf-8')).hexdigest()
        try:
            sql_usr = '''
                update account set password=%s where name=%s
                    '''
            c.execute(sql_usr,(md5_passwd, usr))
            conn.commit()
            c.close()
            conn.close()
            return '您%s的账号已经将密码修改为%s，请牢记您的密码！！！！！' % (usr, new_passwd)
        except Exception as e:
            conn.rollback()
            c.close()
            conn.close()
            return e

    def char_save(self, usr, passwd):
        if len(usr) == 0 or len(passwd) == 0:
            return '输入的信息不能为空！！！'
        try:
            conn = pymysql.connect(user='root', password=myconf.config['DB_PASSWORD'], host=myconf.config['IP'],
                                   database='tlbbdb', port=myconf.config['DB_PORT'])
            c = conn.cursor()
            conn_web = pymysql.connect(user='root', password=myconf.config['DB_PASSWORD'], host=myconf.config['IP'],
                                       database='web', port=myconf.config['DB_PORT'])
            c_web = conn_web.cursor()
        except:
            return '配置文件的数据库信息填写错误！！请检查您的数据库IP、密码和端口是否填写正确，然后重新执行run.sh脚本！！'

        # 检察角色是否存在
        usr = usr + '@game.sohu.com'
        real_pwd = hashlib.md5(passwd.encode('utf-8')).hexdigest()
        sql_usr = '''
            select accname from t_char where accname = %s;
                '''
        try:
            z = c.execute(sql_usr,usr)
            if z == 0:
                c.close()
                conn.close()
                c_web.close()
                conn_web.close()
                return '检查到对应账号不存在任何角色，请重新输入！！！！'
        except Exception as e:
            c.close()
            conn.close()
            c_web.close()
            conn_web.close()
            return e

        # 检查密码是否正确

        pwd_sql = '''
            select name,password from account where name=%s and password=%s;
            '''
        try:
            jc = c_web.execute(pwd_sql, (usr, real_pwd))
            if jc == 0:
                return '账号不存在或密码输入错误！！！请重新确认！！！！'
        except Exception as e:
            c.close()
            conn.close()
            c_web.close()
            conn_web.close()
            return e
        sql_find = '''
            update t_char set scene=2,xpos=16000,zpos=17000 where accname=%s;
        '''
        try:
            c.execute(sql_find,usr)
            conn.commit()
            c.close()
            conn.close()
            c_web.close()
            conn_web.close()
            return '自救成功！！！！赶快上线看看吧！！！'
        except Exception as e:
            conn.rollback()
            c.close()
            conn.close()
            c_web.close()
            conn_web.close()
            return e
    @check_on
    def block_over(self, usr, password):
        if len(usr) == 0 or len(password) == 0:
            return '输入的信息不能为空！！！'
        try:
            conn_tlbbdb = pymysql.connect(user='root', password=myconf.config['DB_PASSWORD'], host=myconf.config['IP'],
                                          database='tlbbdb', port=myconf.config['DB_PORT'])
            c_tlbbdb = conn_tlbbdb.cursor()
            conn_web = pymysql.connect(user='root', password=myconf.config['DB_PASSWORD'], host=myconf.config['IP'],
                                       database='web', port=myconf.config['DB_PORT'])
            c_web = conn_web.cursor()
        except:
            return '配置文件的数据库信息填写错误！！请检查您的数据库IP、密码和端口是否填写正确，然后重新执行run.sh脚本！！'

        # 检测账号是否存在
        usr = usr + '@game.sohu.com'
        real_pwd = hashlib.md5(password.encode('utf-8')).hexdigest()
        sql_usr = '''SELECT name,password
        from  account 
        where
        name=%s and password=%s;'''
        try:
            z = c_web.execute(sql_usr,(usr, real_pwd))
            if z == 0:
                c_tlbbdb.close()
                c_web.close()
                conn_tlbbdb.close()
                conn_web.close()
                return '账号不存在，或密码错误，请重新输入！！！'
        except Exception as e:
            c_tlbbdb.close()
            c_web.close()
            conn_tlbbdb.close()
            conn_web.close()
            return e

        # 解封功能
        sql_web = '''
            update account set id_card=null where name=%s;
        '''
        sql_tlbbdb = '''
            update t_char set isvalid=1,settings='0080F5200000040000000173010000017D01000001810100000000000000000000000000000000000116000000012300000002010000000101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000FF0000000000000000000000000000D233000000000000000000000000000128B3420E0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' where accname=%s;
        '''
        try:
            c_web.execute(sql_web,usr)
            conn_web.commit()
            c_tlbbdb.execute(sql_tlbbdb,usr)
            conn_tlbbdb.commit()
            c_tlbbdb.close()
            c_web.close()
            conn_tlbbdb.close()
            conn_web.close()
            return '解封成功！！！！快去登录游戏试试吧！！！！'
        except:
            data = '解封失败:有两种可能性：（1）当前账号无角色，此时账号已经成功解封！；（2）当前账号输入错误'
            conn_web.rollback()
            conn_tlbbdb.rollback()
            c_tlbbdb.close()
            c_web.close()
            conn_tlbbdb.close()
            conn_web.close()
            return data

    @check_on
    def gm_point(self, usr, points):
        if len(usr) == 0 or len(points) == 0:
            return '输入的信息不能为空！！！'
        try:
            conn_web = pymysql.connect(user='root', password=myconf.config['DB_PASSWORD'], host=myconf.config['IP'],
                                       database='web', port=myconf.config['DB_PORT'])
            c_web = conn_web.cursor()
        except:
            return '配置文件的数据库信息填写错误！！请检查您的数据库IP、密码和端口是否填写正确，然后重新执行run.sh脚本！！'
        # 检测账号是否存在
        usr = usr + '@game.sohu.com'
        sql_usr = '''SELECT name
        from  account 
        where
        name = %s;'''
        try:
            z = c_web.execute(sql_usr,usr)
            if z == 0:
                c_web.close()
                conn_web.close()
                return '账号不存在，请重新输入！！！'
        except Exception as e:
            c_web.close()
            conn_web.close()
            return e

        # 检测是否输入的十进制数字
        if points.isdecimal():
            points = int(points)
        else:
            c_web.close()
            conn_web.close()
            return '请输入数字！！！'
        check_point = '''
            select point from account where name=%s
        '''
        sql_web = '''
            update account set point=%s where name=%s
        '''
        try:
            c_web.execute(check_point, usr)
            original_ponit = c_web.fetchall()[0][0]
            points = int(original_ponit) + int(points)
            c_web.execute(sql_web,(points, usr))
            conn_web.commit()
            c_web.close()
            conn_web.close()
            return '充值成功！！！！快去登录游戏试试吧！！！！'
        except Exception as e:
            conn_web.rollback()
            c_web.close()
            conn_web.close()
            return e
# if __name__ == '__main__':
#     print('-----------------------------------------------')
#     print('1.输入 register ，则进入 注册账号 选项！！')
#     print('2.输入 modify_passwd ，则进入 修改账号密码 选项！！！！')
#     print('3.输入 char_save ，则进入 地图自救 选项！！！！')
#     print('4.输入 block_over ，则进入 自助解封 选项！！！！')
#     print('后续将有其他角色后台功能完善！！！！')
#     print('-----------------------------------------------')
#     usr_choose = input('请输入您的选项：')
#     backstage = Backstage()
#     while not hasattr(backstage,usr_choose):
#         print('没有此项功能，请重新输入！！！！')
#         usr_choose = input('请输入您的选项：')
#     else:
#         func = getattr(backstage, usr_choose)
#         func()
